package cn.yunyichina.provider.base.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import cn.yunyichina.provider.base.dao.ApiDao;
import cn.yunyichina.provider.base.entity.Api;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 * 接口表服务实现
 */
@Service
public class ApiServiceImpl {

    @Autowired
    private ApiDao apiDao;

    public ResponseObject listApi(String data) {
        Api wheres = null ;
        if(StringUtils.isNotBlank(data)) {
            wheres = JsonUtils.parseObject(data, Api.class);
        }

        ResponseObject response = new ResponseObject();
        response.setResultCodeAndMessage("0", "调用成功");
        List<Api> list = apiDao.select(wheres);
        response.setResultObject(list);
        return response;
    }
    
    public ResponseObject getApi(String data) {
        Api wheres = null ;
        if(StringUtils.isNotBlank(data)) {
            wheres = JsonUtils.parseObject(data, Api.class);
        }

        ResponseObject response = new ResponseObject();
        response.setResultCodeAndMessage("0", "调用成功");
        List<Api> list = apiDao.select(wheres);
        if(CollectionUtils.isEmpty(list)){
            response.setResultCodeAndMessage("1001", "不存在该接口定义");
            return response;
        }
        response.setResultObject(list.get(0));
        return response;
    }

    public ResponseObject AddApi(String data) {
        Api api= JsonUtils.parseObject(data, Api.class);
        api.setId(PKGenerator.generateId());
        api.setCreatedTime(DateUtils.dateToString(new Date()));
        ResponseObject response = new ResponseObject();
        response.setResultCodeAndMessage("0", "保存成功");
        apiDao.insert(api);
        return response;
    }

    public ResponseObject updateApi(String data) {
        Api api = JsonUtils.parseObject(data, Api.class);
        ResponseObject response = new ResponseObject();
        if(StringUtils.isBlank(api.getId())){
            response.setResultCodeAndMessage("1001", "更新id参数不能为空");
            return response;
        }
        response.setResultCodeAndMessage("0", "更新成功");
        apiDao.update(api);
        return response;
    }

    public ResponseObject deleteApi(String data) {
        Api api = JsonUtils.parseObject(data, Api.class);
        ResponseObject response = new ResponseObject();
        if(StringUtils.isBlank(api.getId())){
            response.setResultCodeAndMessage("1001", "删除id参数不能为空");
            return response;
        }
        response.setResultCodeAndMessage("0", "删除成功");
        apiDao.delete(api);
        return response;
    }
}
